package com.byb.server.web.rest;

import com.codahale.metrics.annotation.Timed;
import com.byb.server.service.SexService;
import com.byb.server.web.rest.util.HeaderUtil;
import com.byb.server.web.rest.util.PaginationUtil;
import com.byb.server.service.dto.SexDTO;
import io.swagger.annotations.ApiParam;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URI;
import java.net.URISyntaxException;

import java.util.List;
import java.util.Optional;
import java.util.stream.StreamSupport;

import static org.elasticsearch.index.query.QueryBuilders.*;

/**
 * REST controller for managing Sex.
 */
@RestController
@RequestMapping("/api")
public class SexResource {

    private final Logger log = LoggerFactory.getLogger(SexResource.class);

    private static final String ENTITY_NAME = "sex";

    private final SexService sexService;

    public SexResource(SexService sexService) {
        this.sexService = sexService;
    }

    /**
     * POST  /sexes : Create a new sex.
     *
     * @param sexDTO the sexDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new sexDTO, or with status 400 (Bad Request) if the sex has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/sexes")
    @Timed
    public ResponseEntity<SexDTO> createSex(@RequestBody SexDTO sexDTO) throws URISyntaxException {
        log.debug("REST request to save Sex : {}", sexDTO);
        if (sexDTO.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new sex cannot already have an ID")).body(null);
        }
        SexDTO result = sexService.save(sexDTO);
        return ResponseEntity.created(new URI("/api/sexes/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /sexes : Updates an existing sex.
     *
     * @param sexDTO the sexDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated sexDTO,
     * or with status 400 (Bad Request) if the sexDTO is not valid,
     * or with status 500 (Internal Server Error) if the sexDTO couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/sexes")
    @Timed
    public ResponseEntity<SexDTO> updateSex(@RequestBody SexDTO sexDTO) throws URISyntaxException {
        log.debug("REST request to update Sex : {}", sexDTO);
        if (sexDTO.getId() == null) {
            return createSex(sexDTO);
        }
        SexDTO result = sexService.save(sexDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, sexDTO.getId().toString()))
            .body(result);
    }

    /**
     * GET  /sexes : get all the sexes.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of sexes in body
     */
    @GetMapping("/sexes")
    @Timed
    public ResponseEntity<List<SexDTO>> getAllSexes(@ApiParam Pageable pageable) {
        log.debug("REST request to get a page of Sexes");
        Page<SexDTO> page = sexService.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/sexes");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

    /**
     * GET  /sexes/:id : get the "id" sex.
     *
     * @param id the id of the sexDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the sexDTO, or with status 404 (Not Found)
     */
    @GetMapping("/sexes/{id}")
    @Timed
    public ResponseEntity<SexDTO> getSex(@PathVariable Long id) {
        log.debug("REST request to get Sex : {}", id);
        SexDTO sexDTO = sexService.findOne(id);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(sexDTO));
    }

    /**
     * DELETE  /sexes/:id : delete the "id" sex.
     *
     * @param id the id of the sexDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/sexes/{id}")
    @Timed
    public ResponseEntity<Void> deleteSex(@PathVariable Long id) {
        log.debug("REST request to delete Sex : {}", id);
        sexService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

    /**
     * SEARCH  /_search/sexes?query=:query : search for the sex corresponding
     * to the query.
     *
     * @param query the query of the sex search
     * @param pageable the pagination information
     * @return the result of the search
     */
    @GetMapping("/_search/sexes")
    @Timed
    public ResponseEntity<List<SexDTO>> searchSexes(@RequestParam String query, @ApiParam Pageable pageable) {
        log.debug("REST request to search for a page of Sexes for query {}", query);
        Page<SexDTO> page = sexService.search(query, pageable);
        HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/sexes");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

}
